﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Com.Lancetinc.Evs.Helpers
{
    public static class StreamUtil
    {
        public static void CopyStream(Stream input, Stream output)
        {
            // Insert null checking here for production
            byte[] buffer = new byte[8192];

            int bytesRead;
            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }

        /// <summary>
        /// 根据资源名称的结尾部分取得全称
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="endWithStr"></param>
        /// <returns></returns>
        public static string GetFullManifestResourceName(this Assembly assembly, string endWithStr)
        {
            var name = assembly.GetManifestResourceNames()
                .FirstOrDefault(x => x.EndsWith(endWithStr));

            if (name != null)
                return name;

            // 如果找不到完全匹配，则不区分大小写查找
            return assembly.GetManifestResourceNames()
                .FirstOrDefault(x => x.EndsWith(endWithStr, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 取得资源名称对应Stream
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="endWithStr"></param>
        /// <returns></returns>
        public static Stream GetManifestResourceStreamEx(this Assembly assembly, string endWithStr)
        {
            var fullName = GetFullManifestResourceName(assembly, endWithStr);
            if (fullName == null) return null;
            return assembly.GetManifestResourceStream(fullName);
        }

        /// <summary>
        /// 把Stream转换为字符串
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="ecd"></param>
        /// <param name="keepOpen">true：不关闭stream</param>
        /// <returns></returns>
        public static string StreamToString(Stream stream, Encoding ecd = null, bool keepOpen = true)
        {
            ecd ??= Encoding.UTF8;
            var reader = new StreamReader(stream, ecd);
            string text = reader.ReadToEnd();
            if (!keepOpen)
            {
                stream.Close();
                stream.Dispose();
            }
            return text;
        }
    }
}
